package com.github.codemperor.core.oss;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

import java.io.InputStream;

public class OssConfig {
    private Logger log = LoggerFactory.getLogger(this.getClass());

    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;

    public Logger getLog() {
        return log;
    }

    public void setLog(Logger log) {
        this.log = log;
    }

    public String getEndpoint() {
        return endpoint;
    }

    public void setEndpoint(String endpoint) {
        this.endpoint = endpoint;
    }

    public String getAccessKeyId() {
        return accessKeyId;
    }

    public void setAccessKeyId(String accessKeyId) {
        this.accessKeyId = accessKeyId;
    }

    public String getAccessKeySecret() {
        return accessKeySecret;
    }

    public void setAccessKeySecret(String accessKeySecret) {
        this.accessKeySecret = accessKeySecret;
    }

    private OSS initOss() {
        log.debug("[OssConfig] endpoint: {}, accessKeyId: {}, accessKeySecret: {}", endpoint, accessKeyId, accessKeySecret);
        return new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    }

    /**
     * 简单上传
     */
    public FileResponse upload(InputStream inputStream, String bucketName, String objectName) {
        OSS client = initOss();
        PutObjectResult result = client.putObject(bucketName, objectName, inputStream);
        FileResponse res = new FileResponse();
        BeanUtils.copyProperties(result, res);
        log.debug("file result: {}", res);
        return res;
    }
}
